package com.kehutong.house.service;

import com.kehutong.house.entity.Community;
import com.kehutong.house.entity.House;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.Objects;


@WebService("/basic/house/service/api")
public class HouseServiceApi {

	static final Logger logger = LoggerFactory.getLogger(HouseServiceApi.class);

	@Inject
	private JdbcSession jdbcSession;

	@ReqMapping("/list")
	public Object list(JSONObject jsonObject) {
		return jdbcSession.findArray(House.class)
					.eq(jsonObject, "communityNo", "buildNo")
					.like(jsonObject, "unitName", "name", "ownerName")
					.order("sort", "desc")
					.exe();
	}

	@ReqMapping("/get")
	public Object get(House house) {
		return house;
	}

	@Bean(newInstance = true, copy = true)
	@ReqMapping("/save")
	public Object save(House house) {
		//房屋是否已经存在
		FindOne<House> find = jdbcSession.findOne(House.class)
				.eq("deleted", false)
				.eq("communityNo", house.getCommunityNo())
				.eq("buildName", house.getBuildName())
				.eq("floorName", house.getFloorName())
				.eq("name", house.getName());

		if (Objects.nonEmpty(house.getUnitName())) {
			find.eq("unitName", house.getUnitName());
		}
		House item = find.exe();

		if (Objects.nonNull(item)) {
			return Result.error(0, "当前楼栋下已有相同的房屋信息，请修改后重试");
		}
		jdbcSession.insert(house);
		return Result.success(house);
	}

	@Bean(copy = true)
	@ReqMapping("/update")
	public Object update(House house) {
		FindOne<House> find = jdbcSession.findOne(House.class)
				.eq("deleted", false)
				.eq("communityNo", house.getCommunityNo())
				.eq("buildName", house.getBuildName())
				.eq("floorName", house.getFloorName())
				.eq("name", house.getName())
				.noEq("id", house.getId());

		if (Objects.nonEmpty(house.getUnitName())) {
			find.eq("unitName", house.getUnitName());
		}
		House item = find.exe();

		if (Objects.nonNull(item)) {
			return Result.error(0, "当前楼栋下已有相同的房屋信息，请修改后重试");
		}
		jdbcSession.updateById(house);

		return Result.success(house);
	}
	@ReqMapping("/houseList")
	public Object houseList(JSONObject json) {
		logger.debug("{}=========", this.hashCode());
		Page<House> page = jdbcSession.findPage(House.class)
				.eq("deleted", false)
				.eq(json,"id")
				.between("createTime", json, "beginTime", "endTime")
				.like(json, "unitName", "communityName")
				.page(json).exe();
		return page;
	}
	@ReqMapping("/delete")
	public Object delete(House house) throws Exception {
		house.setDeleted(true);
		return jdbcSession.updateById(house);
	}

}
